<!-- author: lizq -->
<!-- date: 2023-03-01 15:09:44 -->
<!-- description: table -->

<template>
  <!-- 列表 -->
  <el-table
    v-if="tableShow"
    ref="refTable"
    v-loading="loading"
    :height="height ? height : setHeight"
    :data="tableData"
    :header-cell-style="{ backgroundColor: '#FFF4E5 !important' }"
    :style="{ 'width:': tableInfo.width ? tableInfo.width : width }"
    :row-key="tableInfo.rowKey ? tableInfo.rowKey : rowKey"
    :default-expand-all="isExpandAll"
    :expand-row-keys="tableInfo.expandRowKeys ? tableInfo.expandRowKeys : expandRowKeys"
    :stripe="tableInfo.stripe ? tableInfo.stripe : stripe"
    :border="tableInfo.border ? tableInfo.border : border"
    :show-summary="tableInfo.showSummary ? tableInfo.showSummary : showSummary"
    :sum-text="tableInfo.sumText ? tableInfo.sumText : sumText"
    :summary-method="tableInfo.summaryMethod ? tableInfo.summaryMethod : summaryMethod"
    @selection-change="tableSelection"
    @expand-change="tableExpand"
  >
    <!-- 多选 -->
    <el-table-column v-if="tableInfo.isSelect" fixed="left" type="selection" width="55" :reserve-selection="true" align="center" />
    <el-table-column
      v-else-if="tableInfo.isSelect == undefined"
      :fixed="tableInfo.selectFixed ? tableInfo.selectFixed : 'left'"
      type="selection"
      width="55"
      :align="'center'"
    />
    <!-- 序号 -->
    <el-table-column v-if="pageNumber" type="index" label="序号" width="55" align="center">
      <template #default="{ $index }">
        {{ $index + pageNumber }}
      </template>
    </el-table-column>
    <!-- 列-内容-默认 -->
    <template v-if="!isInput">
      <tableColumnItem
        v-for="(item, index) in tableHeader"
        :key="index"
        :col="item"
        :state-power="tableInfo.statePower"
        :custom-column="customColumn"
        @call-back-data="tableOperate"
      >
        <template v-for="slot in Object.keys(customSlots)" #[slot]="scope">
          <!-- 以之前的名字命名插槽，同时把数据原样绑定 -->
          <slot :name="slot" v-bind="scope" />
        </template>
      </tableColumnItem>
    </template>
    <!-- 列-内容-input -->

    <template v-if="isInput">
      <tableColumnItemInput
        v-for="(item, index) in tableHeader"
        :key="index"
        :col="item"
        :state-power="tableInfo.statePower"
        :custom-column="customColumn"
        @call-back-data="tableOperate"
      >
        <template v-for="slot in Object.keys(customSlots)" #[slot]="scope">
          <!-- 以之前的名字命名插槽，同时把数据原样绑定 -->
          <slot :name="slot" v-bind="scope" />
        </template>
      </tableColumnItemInput>
    </template>
    <!-- 操作-slot -->
    <el-table-column
      v-if="tableInfo.customOperate"
      label="操作"
      :align="'center'"
      :width="tableInfo.operateWidth ? tableInfo.operateWidth : operateWidth"
      fixed="right"
    >
      <template #default="scope">
        <slot name="operateColumn" :index="scope.$index" :row="scope.row"></slot>
      </template>
    </el-table-column>
    <!-- 操作-list -->
    <el-table-column v-else-if="isOperate" label="操作" :align="'center'" :width="tableInfo.operateWidth ? tableInfo.operateWidth : operateWidth" fixed="right">
      <template #default="scope">
        <div class="table-operation">
          <!-- <span v-for="(item, i) in formatButtonData(tableInfo.operateBut)" :key="i"> -->
          <span v-for="(item, i) in tableInfo.operateBut" :key="i">
            <!-- 判断是否显示当前行的 操作按钮 -->
            <span v-if="isScopeRow(scope.$index)">
              <!-- 分隔符 -->
              <span v-if="i != 0" v-hasPermi="[item.power]" class="split"></span>
              <!-- link 按钮 -->
              <el-button
                v-if="item.text != '更多'"
                v-hasPermi="[item.power]"
                :disabled="setDisabled(item.power, scope.row)"
                link
                :type="setType(item.text)"
                @click="tableOperate(scope.row, i + 1)"
              >
                <i :class="item.icon"></i> {{ item.text }}
              </el-button>
              <!-- 更多 下拉 -->
              <el-dropdown v-else trigger="click">
                <span class="el-dropdown-link">
                  {{ item.text }}<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item v-for="(a, s) in item.list" :key="s" @click="tableOperate(scope.row, i + s + 1)">{{ a }}</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </span>
          </span>
        </div>
      </template>
    </el-table-column>
    <!-- 表格外加-按钮 -->
    <template v-if="tailButton" #append>
      <!-- dashed -->
      <el-button style="width: 100%; border: 1px solid #e5e6eb; margin-top: 9px; color: #444444" type="text" @click="handleTailButton">
        <el-icon style="margin-right: 6px"><Plus /></el-icon>
        {{ tailButtonTitle }}
      </el-button>
    </template>
  </el-table>
</template>
<script setup>
// import { useSystemStore } from "@/store/system";
import { nextTick, watch } from "vue";
import tableColumnItem from "./table-column-item.vue";
import tableColumnItemInput from "./table-column-item-input.vue";
import useAppStore from "@/store/modules/app";
const appStore = useAppStore();
// const $systemStore = useSystemStore();
// import { checkPermi } from "@/utils/permission"; // 权限判断函数
const $props = defineProps({
  tableData: {
    type: Array,
    default: () => []
  },
  tableHeader: {
    type: Array,
    default: () => []
  },
  tableInfo: {
    type: Object,
    default: () => {}
  },
  loading: {
    type: Boolean,
    default: false
  },
  pageNo: {
    type: Number,
    default: 0
  },
  pageSize: {
    type: Number,
    default: 0
  },
  customColumn: {
    type: Boolean,
    default: false
  },
  tailButton: {
    type: Boolean,
    default: false
  },
  tailButtonTitle: {
    type: String,
    default: "新增"
  },
  isInput: {
    type: Boolean,
    default: false
  },
  height: {
    type: String,
    default: ""
  }
});
const $emit = defineEmits(["callBackData"]);
const formSearchHeight = computed(() => appStore.formSearch.height);
// 表格列插槽
const { proxy } = getCurrentInstance();
const customSlots = reactive({
  ...proxy.$slots
});

//分页参数
const pageNumber = computed(() => {
  if ($props.pageNo && $props.pageSize) {
    return ($props.pageNo - 1) * $props.pageSize + 1;
  } else {
    return 0;
  }
});

const refTable = ref(null);
const state = reactive({
  tableShow: true,
  //初始化-tableInfo
  isExpandAll: true,
  expandRowKeys: [],
  width: "100%",
  rowKey: "id",
  stripe: false,
  border: false,
  isOperate: true, // operate = true, 必写项 slot / operateBut, 二选一
  operateBut: [], //// 索引 + 1 = operate(val,i) 中的 i
  operateWidth: 200,
  setHeight: "auto",
  showSummary: false,
  sumText: "合计",
  summaryMethod: () => {}
});
const { tableShow, isExpandAll, expandRowKeys, width, rowKey, stripe, border, isOperate, operateWidth, setHeight } = toRefs(state);

onMounted(() => {
  isOperateShow();
  // table 展开/收起 -- 传参赋值
  if (!$props.tableInfo.isExpandAll) {
    state.isExpandAll = $props.tableInfo.isExpandAll;
  }
});
// 表格最后一行   加的按钮
const handleTailButton = () => {
  $emit("callBackData", "", "00");
};

//table-操作
const tableOperate = (val, i) => {
  console.log(val, i, "ssfdsdfsdf");
  $emit("callBackData", val, i);
};

//table-多选
const tableSelection = (val) => {
  console.log(val, "tableSelection");

  $emit("callBackData", val, "tableSelection");
};

//table-展开/收起
const tableResh = () => {
  // state.tableShow = false;
  state.isExpandAll = !state.isExpandAll;
  if (state.isExpandAll) {
    // state.setHeight = "calc(100% - 125px)";
    tableExpand();
  } else {
    state.tableShow = false;
    state.setHeight = "auto";
    nextTick(() => {
      state.tableShow = true;
    });
  }
};

watch(
  () => formSearchHeight.value,
  () => {
    tableExpand();
  }
);
watch(
  () => $props.tableData,
  () => {
    tableExpand();
  }
);
// keepAlive监听
onActivated(() => {
  tableExpand();
});

//展开行
const tableExpand = () => {
  state.setHeight = "auto";

  nextTick(() => {
    let clientHeight = refTable.value.$el.offsetHeight;
    let innerHeight = window.innerHeight;
    // 标签栏高度 90px
    // container 边框 20px
    // 操作栏 32px  margin-bottom 20px
    // 搜索栏   margin-bottom 40px
    // 分页 32px margin-top 20px
    let calculatedHigh = null;

    if ($props.pageNo && $props.pageSize) {
      calculatedHigh = innerHeight - formSearchHeight.value - 316;
    } else {
      // calculatedHigh = innerHeight - formSearchHeight.value - 238;
      calculatedHigh = innerHeight - formSearchHeight.value - 258;
    }

    if (clientHeight >= calculatedHigh) {
      state.setHeight = calculatedHigh;
    } else {
      state.setHeight = "auto";
    }
  });
};
//清空勾选
const clearSelection = () => {
  refTable.value.clearSelection();
};

//table-but-type
const setType = (val) => {
  if (val.indexOf("删除") !== -1) {
    return "danger";
  } else {
    return "primary";
  }
};
//判定按钮的启用/禁用
const setDisabled = (val, obj) => {
  if (val == "A" && obj.status == "1") {
    return true;
  }
};

//根据操作栏是否有按钮，判断操作栏是否显示
const isOperateShow = () => {
  let showFlag = false;
  let operateBut = $props.tableInfo.operateBut;
  let btnList = {};
  if (Array.isArray(operateBut) && operateBut.length) {
    // let btnList = {};
    // 特殊权限无字符标识
    operateBut.forEach((item) => {
      if (item.power != "") {
        btnList[item.power] = true;
      } else {
        showFlag = true;
      }
    });

    // 基本权限比对vuex权限字符
    // let storeBtn = $systemStore.button;
    // if (!showFlag && storeBtn.length) {
    //   showFlag = storeBtn.some((key) => {
    //     return btnList[key];
    //   });
    // }
  }
  // state.isOperate =  showFlag;
  state.isOperate = Object.keys(btnList).length != 0 ? true : showFlag;
};

//控制当前行的操作栏-显隐
const isScopeRow = (val) => {
  let pageNumber = val + ($props.pageNo - 1) * $props.pageSize;
  if ($props.tableInfo.hideRowKey) {
    return $props.tableInfo.hideRowKey.indexOf(pageNumber) == -1;
  } else {
    return true;
  }
};

const getSelectionRows = (row) => {
  refTable.value.toggleRowSelection(row);
};

// 处理数据 去除没有权限的按钮
// const formatButtonData = (list) => {
//   const filteredList = list.filter((item) => checkPermi([item.power]));
//   return filteredList;
// };

defineExpose({ clearSelection, tableResh, getSelectionRows, tableExpand });
</script>

<style scoped lang="scss">
.el-dropdown {
  margin-top: 4px;
  cursor: pointer;
}

:deep(.el-table__inner-wrapper) {
  height: 100% !important;
}
</style>
